<!--
 * @Author: qwlbwm 18370818801qwl./
 * @Date: 2023-09-06 13:36:58
 * @LastEditors: qwlbwm 18370818801qwl./
 * @LastEditTime: 2023-09-28 11:28:09
 * @FilePath: \checc-business-module-web-kgpt-dev\src\views\examineManage\components\editAddStandardIndex.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 通用的评分管理（包括中交和中咨） -->
  <div>
    <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      width="1100px"
      :before-close="beforeClose"
      title="评分管理"
    >
      <div class="examine-dialog-content" v-if="currentScoreCompose">
        <el-tabs v-model="tabActive" @tab-click="tabClick">
          <el-tab-pane
            :label="item.composeItem_text"
            v-for="item in scoreComposeArr"
            :key="item.id"
            :name="item.id"
          ></el-tab-pane>
        </el-tabs>
        <el-row class="" style="margin-bottom: 20px">
          <el-col :span="16" align="left">
            <span>计分规则:</span>
            <el-select
              v-model="currentScoreCompose.scoreRule"
              @change="scoreRuleChange"
              style="width: 300px"
              size="small"
              placeholder="计分规则"
              :disabled="pageDisabled"
            >
              <el-option
                v-for="item in dict_scoreRules"
                :key="item.itemValue"
                :label="item.itemText"
                :value="item.itemValue"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col
            :span="8"
            align="right"
            v-if="currentScoreCompose.scoreRule !== '4'"
           
          >
            <el-button type="danger" @click="handleDelete()">删除</el-button>
            <el-button type="primary" @click="handleAdd()" >新增项</el-button>
          </el-col>
        </el-row>
        <div v-if="currentScoreCompose.scoreRule !== '4'">
          <el-table
            :data="currentScoreCompose.composeItemSetList"
            style="width: 100%"
            v-loading="table_loading"
            row-key="id"
            border
            height="300px"
            @selection-change="selectionChange"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column prop="number" align="left" width="140" label="编号" />
            <el-table-column prop="name" align="center" label="配置项" />
            <el-table-column prop="setType_text" align="center" label="类型" />
            <el-table-column prop="standardFactor" align="center" label="标准系数">
              <template #default="scope">
                <span v-if="scope.row.setType === '2'">{{
                  scope.row.standardFactor
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="joinFactor" align="center" label="参与方式系数">
              <template #default="scope">
                <span v-if="scope.row.setType === '2'">{{
                  filterJoinMethod(scope.row.joinFactor)
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="rankFactor" align="center" label="排名系数">
              <template #default="scope">
                <span v-if="scope.row.setType === '2'">{{
                  filterRankFactor(scope.row.rankFactor)
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="intro" align="center" label="配置项说明" />
            <el-table-column label="操作" align="center" width="120px">
              <template #default="scope">
                <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">关闭</el-button>
        </span>
      </template>
      <itemAddAndEdit
        v-model:visible="addEditVisible"
        @refresh="refresh"
        :op-type="opType"
        :edit-form="handleItemRow"
        :compose-item-data="currentScoreCompose"
        :index-handle-data="handleRow"
        :prop-dict="dict_datas"
        :apiPackage="apiPackage"
        :pageDisabled="pageDisabled"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { dataDictionary } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, defineComponent, reactive, ref, toRefs, watch } from "vue";
import * as api from "../../../api/examineManage";
import itemAddAndEdit from "./itemAddAndEdit.vue";
interface ItemSet {
  id: string;
  [propName: string]: any;
}
export default defineComponent({
  components: {
    itemAddAndEdit,
  },
  emits: {
    "update:visible": null,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true, // 必传项
    },
    standardType: {
      type: String, //1中交还是2中资
      default: "1",
    },
    handleRow: {
      //处理的指标数据
      type: Object,
    },
    apiPackage: {
      //全部接口打包必须包含{detail:'',score:'',insert:'',update:'',deletel:''}
      type: Object,
      default: () => {
        return {
          detail: "", //查询评分管理详情接口
          score: "", //更新计分接口
          insert: "", //新增配置项接口
          update: "", //更新配置项接口
          delete: "", //删除配置项接口
        };
      },
      required: true, // 必传项
    },
    pageDisabled: {
      //页面是否只可以看不能操作
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const dialogVisible = computed(() => {
      return props.visible;
    });
    const selectedRows = ref<Array<ItemSet>>([]);
    const dict_datas = reactive({
      dict_ranklist: [],
      dict_joinMethods: [],
    });
    const state = reactive<any>({
      //整体数据带dict全是字典查询
      scoreComposeArr: [],
      currentScoreCompose: null, //当前tab选中的组成详情
      tabActive: "",
      addEditVisible: false,
      dict_scoreRules: [],

      handleItemRow: null, //处理的配置项数据
      table_list: [],
      opType: "add", //操作方式 add/edit
      table_loading:false
    });
    const beforeClose = () => {
      cancel();
    };
    const getApiPackage = () => {
      return props.apiPackage;
    };
    const scoreRuleChange = (value) => {
      state.checked=value
      // state.currentScoreCompose.scoreRule=value
      console.log(state.currentScoreCompose)
      //计分规则改变
      api[props.apiPackage.score]({
        id: state.currentScoreCompose.id,
        scoreRule: value,
      }).then((res) => {
        if ((res.data as any).success) {
          ElMessage({
            message: "已更改计分规则",
            type: "success",
          });
        }
      });
    };
    const selectionChange = (arr) => {
      //选中
      selectedRows.value = arr;
    };
    const tabClick = (TabsPaneContext) => {
      state.currentScoreCompose = state.scoreComposeArr[TabsPaneContext.index];
    };
    const cancel = () => {
      state.handleItemRow = null;
      emit("update:visible", false);
    };
    const confirm = () => {
      //确定新增或修改
    };
    const handleAdd = () => {
      state.opType = "add";
      state.handleItemRow = null;
      state.addEditVisible = true;
    };
    const handleEdit = (item) => {
      state.opType = "edit";
      state.handleItemRow = item;
      state.addEditVisible = true;
    };
    const handleDelete = () => {
      if (selectedRows.value.length === 0) {
        ElMessage({
          message: "请选择数据后删除！",
          type: "warning",
        });
      } else if (selectedRows.value.length > 1) {
        ElMessage({
          message: "请选择一条数据！",
          type: "warning",
        });
      } else {
        ElMessageBox.confirm("确定要删除选中数据吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // let sel_ids=selectedRows.value.map(item=>{return item.id});
          api[props.apiPackage.delete]({
            id: selectedRows.value[0].id,
          }).then((res) => {
            if (res.data.code == 200) ElMessage.success("删除成功");
            getScoreDetail(state.tabActive);
          });
        });
      }
    };
    const filterRankFactor = (rank) => {
      let str = "";
      if (rank) {
        for (const key in rank) {
          if(key){
            let a: any = dict_datas.dict_ranklist.find(
            (item: any) => item.itemValue === key
          );
          str += a.itemText + `(${rank[key]})`;
          }
         
        }
      }
      return str;
    };
    const filterJoinMethod = (mt) => {
      let str = "";
      if (mt) {
        for (const key in mt) {
          let a: any = dict_datas.dict_joinMethods.find(
            (item: any) => item.itemValue === key
          );
          str += a.itemText + `(${mt[key]})`;
        }
      }
      return str;
    };
    watch(
      () => props.visible,
      (newval) => {
        if (newval) {
          getScoreDetail();
        }
      }
    );
    const refresh = () => {
      getScoreDetail(state.tabActive);
    };
    const getScoreDetail = (active?) => {
      state.table_loading=true
      //获取评分管理详情列表
      api[props.apiPackage.detail]({
        indexId: props.handleRow?.id, //1-中交标准指标、2-中咨标准指标
      }).then((res) => {
        state.scoreComposeArr = res.data.data;
        if (active) {
          //如果已经在其他tab了就自动切换
          state.currentScoreCompose = res.data.data.find((item) => item.id === active);
        } else {
          state.currentScoreCompose = res.data.data[0];
        }
        state.tabActive = state.currentScoreCompose.id;
        state.table_loading=false
      });
    };
    const getDictDatas = () => {
      let dictIds = [
        "KHGL_COMPOSE_SCORE_RULE_CODE",
        "KHGL_COMPOSE_SET_RANK_CODE",
        "KHGL_COMPOSE_SET_JOIN_METHOD_CODE",
      ];

      dataDictionary(dictIds).then((res) => {
        let response = res.data.data;
        state.dict_scoreRules = response.KHGL_COMPOSE_SCORE_RULE_CODE;
        dict_datas.dict_ranklist = response.KHGL_COMPOSE_SET_RANK_CODE;
        dict_datas.dict_joinMethods = response.KHGL_COMPOSE_SET_JOIN_METHOD_CODE;
      });
    };
    getDictDatas();

    return {
      ...toRefs(state),
      dict_datas,
      dialogVisible,
      getApiPackage,
      beforeClose,
      filterRankFactor,
      filterJoinMethod,
      refresh,
      handleDelete,
      scoreRuleChange,
      selectionChange,
      handleEdit,
      tabClick,
      handleAdd,
      cancel,
      confirm,
    };
  },
});
</script>
<style lang="scss" scoped>
.examine-dialog-content {
  padding: 20px;
}
</style>
